<?php

namespace App\X;


use App\Common\Log;
use EasySwoole\Component\Pool\PoolManager;

/**
 * 连接应用池辅助类
 *
 * Class XDataBase
 * @package App\X
 */
class XDataBase
{
    private $db;
    private $db_pool;

    private $timeout;


    public function __construct($pool, $timeout = 1)
    {
        $this->db_pool = $pool;

        if ($timeout != null)
        {
            $this->timeout = $timeout;
        }

        XContext::funcInsStatic()->set($pool, $this);
    }


    /**
     * 获取数据库存
     *
     * @return mixed
     * @throws \Exception
     */
    public function funcGetDB()
    {
        if (is_null($this->db))
        {
            $reconnect_max = 3; //重连机制
            while ($reconnect_max--)
            {
                $this->funcSetConnect();
                if (!is_null($this->db))
                {
                    //链接成功
                    break;
                }

                //停1秒进去重新链接
                \co::sleep(1);
            }

            if (is_null($this->db))
            {
                Log::funcLogErr(__METHOD__, 'Pool Is Empty');
                throw new \Exception('Pool Is Empty');
            }
        }

        return $this->db;
    }


    /**
     * 回收
     *
     * @throws \Throwable
     */
    public function funcRecycle()
    {
        if ($this->db != null)
        {
            PoolManager::getInstance()
                ->getPool($this->db_pool)
                ->recycleObj($this->db);

            $this->db = null;

            Log::funcLogDebug(__METHOD__, "{$this->db_pool}-回收");
        }
    }


    /**
     * 设置数据库连接池
     */
    private function funcSetConnect()
    {
        $this->db = PoolManager::getInstance()
            ->getPool($this->db_pool)
            ->getObj($this->timeout);
    }

}